package com.blackcat.monitor.tool;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;
import java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;

import com.blackcat.monitor.vo.DataTemplete;

public class HttpQueryManager {

	static Properties configer = new Properties();

	static String url;

	static HttpQueryManager httpQueryManager;

	static HashMap<String, Class<?>> ref; // vo类描述，key为vo信息类路径如001，value为class对象
	

	private ThreadSafeClientConnManager tcm = null;

	private HttpQueryManager() {

		SchemeRegistry schemeRegistry = new SchemeRegistry();
		schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory
				.getSocketFactory()));
		tcm = new ThreadSafeClientConnManager(schemeRegistry);
		tcm.setMaxTotal(5);
		tcm.setDefaultMaxPerRoute(4);

	}

	static {
		ref = new HashMap<String, Class<?>>();
		InputStream in = null;
		InputStream refin = null;
		ClassLoader loader = HttpQueryManager.class.getClassLoader();
		in = loader.getResourceAsStream("Server.properties");
		refin = loader.getResourceAsStream("InfoMapRef.properties");
		try {
			configer.load(in);

			// 通过properties文件加载vo类描述
			Properties refMap = new Properties();
			refMap.load(refin);
			for (Entry t : refMap.entrySet()) {
				ref.put(t.getValue().toString(),
						Class.forName(t.getKey().toString()));
			}
		} catch (IOException e) {
			System.out.println("加载配置文件出错");
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			System.out.println("VO对象加载错误");
			e.printStackTrace();
		}

		url = (String) configer.get("ServerPath");
	}

	public synchronized static HttpQueryManager getInstance() {
		
		if (null == httpQueryManager)
		{
			httpQueryManager= new HttpQueryManager();
		}
	   return httpQueryManager;
	}

	public List<?> httpStrQuery(String queryStr) throws IOException,
			InstantiationException, IllegalAccessException {
		return (httpResultAnalysis(getHttpResult(queryStr)));
		// getHttpResult(queryStr);
		// return null;
	}

	// 通过http请求返回查询结果字符串
	private synchronized String getHttpResult(String queryStr) throws IOException {
		String GET_URL = url + "?qStr=" + queryStr;
		HttpClient httpclient = new DefaultHttpClient(tcm);
		HttpGet httpget = new HttpGet(GET_URL);
		HttpResponse response;
		String result = null;
		try {
			response = httpclient.execute(httpget);
			HttpEntity entity = response.getEntity();
			InputStream instream;
			

			if (entity != null) {
				instream = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(instream));
				result = reader.readLine();
				instream.close();
			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
		 
	   
		
		
		
//		return result;
		// return
		// "001.001.001:123,001.001.002:123,001.001.003:234,001.001.004:897,001.001.005:97,001.001.006:ttf,"
		// +
		// "002.001.001:123,002.001.002:123,002.001.003:234,002.001.004:897,002.001.005:97,002.001.006:ttf";
	}

	// 解析查询结果字符串转换为结果对象
	private List<DataTemplete> httpResultAnalysis(String result)
			throws InstantiationException, IllegalAccessException {

		List<DataTemplete> results = new ArrayList<DataTemplete>();
		if (result == null || result.equals(""))
			return results;

		String[] kvArray = result.split(","); // 将结果分为key:value形式
		String fullPath = (kvArray[0].split(":"))[0];// key值全路径
		String referClass = fullPath
				.substring(4, fullPath.lastIndexOf(".") - 4); // 信息类路径
		Class voClass = ref.get(referClass); // 通过信息类代码除去矿与叶节点如001,获取vo类
		int filedsSize = voClass.getFields().length; // vo类中定义的显示字段数，与信息类叶节点数相同（定义时为public）

		int i = 0;

		DataTemplete obj = (DataTemplete) voClass.newInstance();
		for (String temp : kvArray) {
			obj.setValue(temp.substring(temp.indexOf(":") - 4,
					temp.indexOf(":") - 1),
					temp.substring(temp.indexOf(":") + 1));
			i++;
			if (i == filedsSize) {
				obj.setNodeId(temp.substring(0, 3));
				results.add(obj);
				obj = (DataTemplete) voClass.newInstance();
				i = 0;
			}

		}
		return results;

	}

}
